function benchmark_comparison(case_name)
% 全面的调度结果质量评价脚本
% 输入: case_name (如 'Conv_Case0')

fprintf('=== %s 调度结果质量评价 ===\n', case_name);

%% 1. 加载数据和结果
nodes_file = sprintf('../data/CSV-version/%s_Nodes.csv', case_name);
edges_file = sprintf('../data/CSV-version/%s_Edges.csv', case_name);
c_schedule_file = sprintf('result/Problem1/%s_schedule.txt', case_name);
c_summary_file = sprintf('result/Problem1/%s_summary.txt', case_name);

% 加载图数据
try
    nodes_table = readtable(nodes_file);
    edges_table = readtable(edges_file);
    G = digraph(edges_table.StartNodeId + 1, edges_table.EndNodeId + 1, [], nodes_table);
    fprintf('✅ 图数据加载: %d 节点, %d 边\n', numnodes(G), numedges(G));
catch ME
    fprintf('❌ 图数据加载失败: %s\n', ME.message);
    return;
end

% 读取C语言调度结果
try
    c_schedule = readmatrix(c_schedule_file) + 1; % 转换为MATLAB 1-based索引
    fprintf('✅ C语言调度结果加载: %d 节点\n', length(c_schedule));
catch ME
    fprintf('❌ C语言调度结果读取失败: %s\n', ME.message);
    return;
end

%% 2. 基本质量检查
fprintf('\n=== 基本质量检查 ===\n');

% 完整性检查
if length(c_schedule) ~= numnodes(G)
    fprintf('❌ 调度长度不匹配: 期望%d, 实际%d\n', numnodes(G), length(c_schedule));
else
    fprintf('✅ 调度长度正确: %d\n', length(c_schedule));
end

% 唯一性检查
unique_nodes = unique(c_schedule);
if length(unique_nodes) ~= length(c_schedule)
    fprintf('❌ 调度中有重复节点\n');
else
    fprintf('✅ 调度中所有节点唯一\n');
end

% 节点范围检查
if min(c_schedule) < 1 || max(c_schedule) > numnodes(G)
    fprintf('❌ 调度中有无效节点ID\n');
else
    fprintf('✅ 所有节点ID有效\n');
end

%% 3. 依赖关系验证
fprintf('\n=== 依赖关系验证 ===\n');
edges = table2array(edges_table(:, {'StartNodeId', 'EndNodeId'})) + 1;
schedule_pos = containers.Map('KeyType', 'int32', 'ValueType', 'int32');
for i = 1:length(c_schedule)
    schedule_pos(c_schedule(i)) = i;
end

dependency_violations = 0;
for i = 1:size(edges, 1)
    start_node = edges(i, 1);
    end_node = edges(i, 2);
    start_pos = schedule_pos(start_node);
    end_pos = schedule_pos(end_node);
    
    if start_pos >= end_pos
        dependency_violations = dependency_violations + 1;
        if dependency_violations <= 5  % 只显示前5个违规
            fprintf('  违规: 节点%d(位置%d) -> 节点%d(位置%d)\n', ...
                   start_node-1, start_pos, end_node-1, end_pos);
        end
    end
end

if dependency_violations == 0
    fprintf('✅ 所有依赖关系满足\n');
else
    fprintf('❌ %d 个依赖关系违规\n', dependency_violations);
end

%% 4. 性能指标计算和对比
fprintf('\n=== 性能指标对比 ===\n');

% 编码映射 (与C代码一致)
nodes_table.OpCode = double(categorical(nodes_table.Op));
nodes_table.TypeCode = double(categorical(nodes_table.Type));
categories_op = categories(categorical(nodes_table.Op));
categories_type = categories(categorical(nodes_table.Type));

code_map.op.ALLOC = find(strcmp('ALLOC', categories_op), 1);
code_map.op.FREE = find(strcmp('FREE', categories_op), 1);
code_map.type.L1 = find(strcmp('L1', categories_type), 1);
code_map.type.UB = find(strcmp('UB', categories_type), 1);
code_map.type.L0A = find(strcmp('L0A', categories_type), 1);
code_map.type.L0B = find(strcmp('L0B', categories_type), 1);
code_map.type.L0C = find(strcmp('L0C', categories_type), 1);

% 计算不同基准的V_stay
fprintf('正在计算各种基准的V_stay...\n');

% 基准1: 拓扑排序 (理论下界的粗略估计)
topo_schedule = toposort(G);
[topo_vstay, topo_history] = calculate_max_vstay(topo_schedule, G, code_map);

% 基准2: 随机拓扑排序 (100次取平均)
random_vstays = zeros(100, 1);
for i = 1:100
    random_topo = topo_schedule(randperm(length(topo_schedule)));
    random_vstays(i) = calculate_max_vstay(random_topo, G, code_map);
end
avg_random_vstay = mean(random_vstays);
std_random_vstay = std(random_vstays);

% 基准3: C语言结果验证
[c_vstay, c_history] = calculate_max_vstay(c_schedule, G, code_map);

% 基准4: 简单贪心算法 (按节点大小排序)
greedy_order = 1:numnodes(G);
[~, size_sort_idx] = sort(G.Nodes.Size, 'descend');  % 大的优先
greedy_schedule = size_sort_idx';
if is_valid_topological_order(G, greedy_schedule)
    [greedy_vstay, ~] = calculate_max_vstay(greedy_schedule, G, code_map);
else
    greedy_vstay = inf;
    fprintf('  注意: 简单贪心算法产生无效调度\n');
end

%% 5. 结果汇总和排名
fprintf('\n=== 性能对比结果 ===\n');
fprintf('算法名称              V_stay峰值    改进率(vs拓扑)  相对排名\n');
fprintf('-------------------------------------------------------\n');

results = [
    topo_vstay,     0,                                '基础拓扑排序';
    avg_random_vstay, (topo_vstay-avg_random_vstay)/topo_vstay*100,  '随机拓扑排序(平均)';
    greedy_vstay,   (topo_vstay-greedy_vstay)/topo_vstay*100,       '简单贪心算法';
    c_vstay,        (topo_vstay-c_vstay)/topo_vstay*100,           'C语言优化结果'
];

for i = 1:size(results, 1)
    if results(i, 1) == inf
        fprintf('%-20s     INF         N/A          最差\n', results{i, 3});
    else
        fprintf('%-20s  %8d     %6.2f%%         ', results{i, 3}, results(i, 1), results(i, 2));
        if i == 1
            fprintf('参考基准\n');
        elseif results(i, 1) == min(results(1:end, 1))
            fprintf('⭐ 最优\n');
        elseif results(i, 2) > 50
            fprintf('优秀\n');
        elseif results(i, 2) > 20
            fprintf('良好\n');
        else
            fprintf('一般\n');
        end
    end
end

%% 6. 详细分析
fprintf('\n=== 详细分析 ===\n');
fprintf('随机算法标准差: %.2f (变异系数: %.2f%%)\n', ...
       std_random_vstay, std_random_vstay/avg_random_vstay*100);

if c_vstay < avg_random_vstay - 2*std_random_vstay
    fprintf('✅ C语言结果显著优于随机基线 (超过2个标准差)\n');
else
    fprintf('⚠️  C语言结果未显著超越随机基线\n');
end

% V_stay历史分析
fprintf('\nV_stay历史曲线特征:\n');
fprintf('  初始值: %d\n', c_history(1));
fprintf('  峰值: %d (步骤 %d)\n', max(c_history), find(c_history == max(c_history), 1));
fprintf('  最终值: %d\n', c_history(end));
fprintf('  平均值: %.1f\n', mean(c_history));

%% 7. 可视化对比
figure('Position', [100, 100, 1200, 800]);
subplot(2, 2, 1);
bar([topo_vstay, avg_random_vstay, greedy_vstay, c_vstay]);
set(gca, 'XTickLabel', {'拓扑', '随机', '贪心', 'C优化'});
title('V_{stay} 峰值对比');
ylabel('V_{stay}');

subplot(2, 2, 2);
steps = 1:length(c_history);
plot(steps, c_history, 'b-', 'LineWidth', 1.5);
hold on;
plot(steps, topo_history, 'r--', 'LineWidth', 1);
xlabel('执行步骤'); ylabel('V_{stay}');
title('V_{stay} 历史曲线对比');
legend('C语言优化', '基础拓扑', 'Location', 'best');

subplot(2, 2, 3);
histogram(random_vstays, 20, 'FaceAlpha', 0.7);
xline(c_vstay, 'r-', 'LineWidth', 2, 'Label', 'C优化结果');
xlabel('V_{stay}'); ylabel('频次');
title('随机算法分布 vs C优化结果');

subplot(2, 2, 4);
improvement_pct = (topo_vstay - c_vstay) / topo_vstay * 100;
pie([improvement_pct, 100-improvement_pct], {sprintf('改进 %.1f%%', improvement_pct), sprintf('剩余 %.1f%%', 100-improvement_pct)});
title('相对于基础拓扑的改进比例');

sgtitle(sprintf('%s - 调度质量全面评价', case_name));

%% 8. 保存评价报告
report_file = sprintf('result/Problem1/%s_quality_report.txt', case_name);
fid = fopen(report_file, 'w');
fprintf(fid, '=== %s 调度质量评价报告 ===\n', case_name);
fprintf(fid, '生成时间: %s\n\n', datestr(now));
fprintf(fid, '基本指标:\n');
fprintf(fid, '  C语言V_stay: %d\n', c_vstay);
fprintf(fid, '  拓扑排序V_stay: %d\n', topo_vstay);
fprintf(fid, '  随机平均V_stay: %.1f (±%.1f)\n', avg_random_vstay, std_random_vstay);
fprintf(fid, '  改进率: %.2f%%\n', (topo_vstay-c_vstay)/topo_vstay*100);
fprintf(fid, '  质量评级: %s\n', get_quality_rating(c_vstay, topo_vstay, avg_random_vstay, std_random_vstay));
fclose(fid);

fprintf('\n✅ 评价报告已保存到: %s\n', report_file);
fprintf('✅ 可视化图表已生成\n');

end

%% 辅助函数
function valid = is_valid_topological_order(G, schedule)
    % 简化的拓扑序验证
    valid = true;
    % 这里可以添加更详细的验证逻辑
end

function rating = get_quality_rating(c_vstay, topo_vstay, avg_random, std_random)
    improvement = (topo_vstay - c_vstay) / topo_vstay * 100;
    if c_vstay < avg_random - 2*std_random && improvement > 70
        rating = '优秀 ⭐⭐⭐';
    elseif c_vstay < avg_random - std_random && improvement > 50
        rating = '良好 ⭐⭐';
    elseif improvement > 30
        rating = '合格 ⭐';
    else
        rating = '需改进';
    end
end
